package com.studentstreet.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.studentstreet.R;
import com.studentstreet.entities.GoodsEntity;
import com.studentstreet.tools.HtmlTools;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SyncImageLoader;
import com.studentstreet.tools.dbhelper.OrderDBHelper;

/**
 * @author likebamboo
 * 
 */
public class FavoriteAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private Context mContext;
	private List<GoodsEntity> mModels = new ArrayList<GoodsEntity>();
	private ListView mListView;
	SyncImageLoader syncImageLoader;
	private PreferenceTools prefTools = null;
	private String userName = "";

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Button bt = (Button) msg.obj;
			bt.setBackgroundResource(msg.what == 0 ? null : msg.what);
		}
	};

	public FavoriteAdapter(Context context, ListView listView) {
		mInflater = LayoutInflater.from(context);
		syncImageLoader = new SyncImageLoader();
		mContext = context;
		mListView = listView;
		mListView.setOnScrollListener(onScrollListener);
		prefTools = new PreferenceTools(mContext);
	}

	// 添加 商品
	public void addGoods(List<GoodsEntity> goodsList) {
		for (GoodsEntity goods : goodsList) {
			mModels.add(goods);
		}
	}

	public void clean() {
		mModels.clear();
	}

	@Override
	public int getCount() {
		return mModels.size();
	}

	@Override
	public Object getItem(int position) {
		if (position >= getCount()) {
			return null;
		}
		return mModels.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.goods_item_adapter, null);
		}
		GoodsEntity goods = mModels.get(position);
		convertView.setTag(position);
		ImageView iv = (ImageView) convertView.findViewById(R.id.goods_image);
		TextView goodsNameText = (TextView) convertView
				.findViewById(R.id.goods_name);
		TextView goodsPriceText = (TextView) convertView
				.findViewById(R.id.goods_price);

		TextView saleCountText = (TextView) convertView
				.findViewById(R.id.goods_saleCount);

		RatingBar ratingBar = (RatingBar) convertView
				.findViewById(R.id.goods_rank_RatingBar);

		// 添加or移出购物车
		Button cartButton = (Button) convertView
				.findViewById(R.id.goods_add_favorite);
		cartButton.setBackgroundResource(R.drawable.favorite_cart_d);
		cartButton.setOnClickListener(new CartListener(goods, cartButton));

		// 检查当前商品是否在购物车中
		if (prefTools.isLogin()) {
			Thread isCart = new Thread(new IsCartThread(goods, cartButton));
			isCart.start();
		}

		iv.setBackgroundResource(R.drawable.goods_item_bg);
		goodsNameText.setText(HtmlTools.getGoods(goods.getName(),
				goods.getSellerName()));
		goodsPriceText.setText(HtmlTools.getPrice(mContext, goods.getPrice()
				+ ""));
		saleCountText.setText(HtmlTools.getCount(mContext, goods.getSaleCount()
				+ ""));

		ratingBar.setRating((float) goods.getRank());

		syncImageLoader.loadImage(position, goods.getImageUrl(),
				imageLoadListener);
		return convertView;
	}

	public String getUserName() {
		userName = prefTools.getUserName();
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	SyncImageLoader.OnImageLoadListener imageLoadListener = new SyncImageLoader.OnImageLoadListener() {

		@Override
		public void onImageLoad(Integer t, Drawable drawable) {
			// GoodsEntity model = (GoodsEntity) getItem(t);
			View view = mListView.findViewWithTag(t);
			if (view != null) {
				ImageView iv = (ImageView) view.findViewById(R.id.goods_image);
				iv.setBackgroundDrawable(drawable);
			}
		}

		@Override
		public void onError(Integer t) {
			GoodsEntity model = (GoodsEntity) getItem(t);
			View view = mListView.findViewWithTag(model);
			if (view != null) {
				ImageView iv = (ImageView) view.findViewById(R.id.goods_image);
				iv.setBackgroundResource(R.drawable.goods_item_bg);
			}
		}

	};

	public void loadImage() {
		int start = mListView.getFirstVisiblePosition();
		int end = mListView.getLastVisiblePosition();
		if (end >= getCount()) {
			end = getCount() - 1;
		}
		syncImageLoader.setLoadLimit(start, end);
		syncImageLoader.unlock();
	}

	AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
				syncImageLoader.lock();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
				loadImage();
				// loadImage();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				syncImageLoader.lock();
				break;

			default:
				break;
			}

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}
	};

	// 添加or移除 购物车按钮监听器
	class CartListener implements View.OnClickListener {
		private GoodsEntity goods;
		private Button bt;

		public CartListener(GoodsEntity goods, Button bt) {
			super();
			this.bt = bt;
			this.goods = goods;
		}

		@Override
		public void onClick(View v) {
			// 查看用户是否登录未登录显示登录界面
			if (!prefTools.isLogin()) {
				Toast.makeText(mContext, "你还没登录", Toast.LENGTH_SHORT).show();
				return;
			}
			// 添加or移除 收藏夹线程
			Thread favoriteThread = new Thread(new Runnable() {
				@Override
				public void run() {
					OrderDBHelper dbHelper = new OrderDBHelper(mContext);
					int result = 0;
					if (dbHelper.selectOne(goods.getId(), getUserName()) > 0) {
						if (dbHelper.delete(goods.getId(), getUserName()) > 0) {
							result = R.drawable.favorite_cart_d;
						}

					} else {
						if (dbHelper.saveOrderItem(goods.getId(),
								goods.getSellerId(), getUserName()) > 0) {
							result = R.drawable.favorite_cart_s;
						}
					}

					Message msg = handler.obtainMessage();
					msg.obj = bt;
					msg.what = result;
					handler.sendMessage(msg);
				}
			});
			favoriteThread.start();
		}
	}

	// 查找当前商品是否已添加到购物车中
	class IsCartThread implements Runnable {
		private GoodsEntity goods = null;
		private Button bt;

		public IsCartThread(GoodsEntity goods, Button bt) {
			super();
			this.goods = goods;
			this.bt = bt;
		}

		@Override
		public synchronized void run() {
			OrderDBHelper dbHelper = new OrderDBHelper(mContext);
			int result = R.drawable.favorite_cart_d;
			if (dbHelper.selectOne(goods.getId(), getUserName()) > 0) {
				result = R.drawable.favorite_cart_s;
			}
			Message msg = handler.obtainMessage();
			msg.obj = bt;
			msg.what = result;
			handler.sendMessage(msg);
		}
	}
}
